<template>
  <Drawer>
    <BaseForm />
  </Drawer>
</template>
<script lang="tsx" setup>
import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import { addCorpus, detailCorpus, updateCorpus } from '#/api/agent/corpus';
import { useFormConfigHook } from '#/hooks/useFormConfig';

import { FormSchemas } from '../schemas';

// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
const { newFormConfig } = useFormConfigHook({
  labelkey: 'customer.corpus',
  schema: FormSchemas,
});
// 定义表单
const [BaseForm, baseFormApi] = useVbenForm(newFormConfig as any);

// 定义弹窗
const [Drawer, drawerApi] = useVbenDrawer({
  loading: true, // 不显示加载中状态
  // 表单校验
  async onConfirm() {
    const { type, id } = drawerApi.getData();
    // 提交表单
    const isPass = await baseFormApi.validateAndSubmitForm();
    if (!isPass) return; // 校验不通过
    if (type === 'addData') {
      addOrEditDictionaryHandle(isPass);
    }
    if (type === 'editData') {
      addOrEditDictionaryHandle(isPass, id);
    }
  },
  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 设置默认值
      const { type, id } = drawerApi.getData();
      // 新增打开弹窗时重置表单
      if (type === 'addData') {
        drawerApi.setState({ loading: false });
        baseFormApi.resetForm();
      }
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        getDepartmentDetail(id);
      }
    }
  },
});

/**
 * @author Buke
 * @description 新增或者编辑语料
 * @param {Record<string, any>} formData - 表单数据对象。
 * @param {number} id - 语料ID（可选）。
 * @returns {void}
 */
async function addOrEditDictionaryHandle(
  formData: Record<string, any>,
  id?: number,
): Promise<void> {
  const data = {
    ...formData,
    id,
    status: Number(formData.status),
  };
  id ? await updateCorpus(data) : await addCorpus(data);
  ElMessage.success($t('common.operateSuccess'));
  emit('refresh');
}

/**
 * @author Buke
 * @description 详情数据回显
 * @param {number} id - 要回显的语料ID。
 * @returns {void}
 */
async function getDepartmentDetail(id: any): Promise<void> {
  try {
    drawerApi.setState({ loading: true });
    const res = await detailCorpus(id);

    baseFormApi.setValues({
      ...res.corpusInfo,
      status: String(res.corpusInfo.status),
    });

    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  } catch {
    ElMessage.error($t('common.getInfoFailed'));
    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  }
}
</script>
